from django.shortcuts import render
from apps.users.models import User
from django.views import View
from django.http import JsonResponse
import json, re
from django.contrib.auth import login, logout, authenticate
from django_redis import get_redis_connection
from utils.views import LoginRequiredJSONMixin
from utils.qiniu_storage import storage
# from utils.cos_storage import storage
from Love_house import settings
from utils.response_code import RET

# Create your views here.

class MobileCountView(View):
    """
    判断手机号码是否重复
    """

    def get(self, request, mobile):
        # 1.接收数据
        # 2.业务逻辑
        count = User.objects.filter(mobile=mobile).count()
        # 3.数据响应
        return JsonResponse({'errno': RET.OK, 'count': count, 'errmsg': 'ok'})


class RegisterView(View):
    """
    注册功能
    """

    def post(self, request):
        # 1.接收请求
        data = json.loads(request.body.decode())


        # 2.获取数据
        mobile = data.get('mobile')
        phonecode = data.get('phonecode')
        password = data.get('password')

        # 3.验证数据

        # 3.1 判断参数是否齐全
        if not all([mobile, phonecode, password]):
            return JsonResponse({'errno': RET.PARAMERR, 'errmsg': '参数不全'})

        # 3.3 判断密码格式
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({'errno': RET.PARAMERR, 'errmsg': '密码格式错误'})


        # 3.5 判断手机号码格式
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'errno': RET.PARAMERR, 'errmsg': '手机号码格式错误'})

        # 补充短信验证码的验证
        redis_cli = get_redis_connection('code')
        sms_code_server = redis_cli.get(mobile)

        if not sms_code_server:
            return JsonResponse({'errno': RET.NODATA, 'errmsg': '短信验证码失效'})

        if phonecode != sms_code_server.decode():
            return JsonResponse({'code': RET.DATAERR, 'errmsg': '短信验证码错误'})


        # 4.保存数据
        user = User.objects.create_user(username=mobile,
                                        password=password,
                                        mobile=mobile)

        # 状态保持
        login(request, user)

        # 5.数据响应
        return JsonResponse({'errno': RET.OK, 'errmsg': 'ok'})


class LoginView(View):
    """用户登录"""

    def post(self, request):
        # 1. 接收数据
        data = json.loads(request.body.decode())

        mobile = data.get('mobile')
        password = data.get('password')

        # 2. 验证数据
        if not all([mobile, password]):
            return JsonResponse({'errno': RET.PARAMERR, 'errmsg': '参数不全'})

        # 判断登录用户输入的是用户名还是手机号码
        if re.match(r'^1[3-9]\d{9}$', mobile):
            # 用户名查询字段设置为手机号
            User.USERNAME_FIELD = 'mobile'
        else:
            # 用户名查询字段设置为用户名
            User.USERNAME_FIELD = 'username'

        # 3. 验证用户名和密码是否正确
        # authenticate 传递用户名和密码
        # 如果用户名和密码正确-->返回User信息
        # 如果用户名或密码错误-->返回None
        user = authenticate(username=mobile, password=password)
        if not user:
            return JsonResponse({'errno': RET.DATAERR, 'errmsg': '用户名或密码错误'})

        # 4. session 状态保持
        login(request, user)


        # 6. 返回响应
        response = JsonResponse({'errno': RET.OK, 'errmsg': 'ok'})
        response.set_cookie('mobile', mobile, 3600 * 24 * 15)

        return response


    def get(self, request):
        """判断是否登录"""

        # 1. 判断用户是否登录，需要获取user
        user = request.user
        # 2. 对user进行认证
        if not user.is_authenticated:
            return JsonResponse({"errno": RET.SESSIONERR, "errmsg": "用户未登录"})

        data = {
            "user_id": user.id,
            "name": user.username
        }
        return JsonResponse({"errno": RET.OK, "errmsg": "已登录", "data": data})


    def delete(self, request):
        """退出登录"""
        logout(request)
        response = JsonResponse({'errno': RET.OK, 'errmsg': '退出登录'})
        response.delete_cookie('mobile')
        return response


class UserInfoView(LoginRequiredJSONMixin, View):
    """用户中心"""
    def get(self, request):
        user = request.user
        avatar_url = settings.QINIUYUN_URL + str(user.avatar)
        data = {
                "avatar_url": avatar_url,
                "create_time": user.date_joined,
                "mobile": user.mobile,
                "name": user.username,
                "user_id": user.id
            }
        return JsonResponse({'errno': RET.OK, 'errmsg': 'ok', 'data': data})


class UploadAvatarView(LoginRequiredJSONMixin, View):
    """上传头像"""
    def post(self, request):
        try:
            avatar = request.FILES.get('avatar')
            avatar = avatar.read()
            ret_key = storage(avatar)
        except Exception as e:
            return JsonResponse({'errno': RET.DATAERR, 'errmsg': '数据错误'})
        request.user.avatar = ret_key
        request.user.save()
        avatar_url = settings.QINIUYUN_URL + ret_key
        return JsonResponse({'errno': RET.OK, 'errmsg': '头像上传成功', 'data': {'avatar_url': avatar_url}})


# class UploadAvatarView(View):
#     """上传头像"""
#     def post(self, request):
#         try:
#             avatar = request.FILES.get('avatar')
#             avatar = avatar.read()
#             ret_key = storage(avatar)
#         except Exception as e:
#             return JsonResponse({'errno': RET.DATAERR, 'errmsg': '数据错误'})
#         request.user.avatar = ret_key
#         request.user.save()
#         # avatar_url = settings.QIINIUYUN_URL + ret_key
#         avatar_url = 'https://carpenter-1256143690.cos.ap-chongqing.myqcloud.com/ihome-avatar.jpg'
#         return JsonResponse({'errno': RET.OK, 'errmsg': '头像上传成功', 'data': {'avatar_url': avatar_url}})


class ModifyNameView(LoginRequiredJSONMixin, View):
    """修改用户名"""
    def put(self, request):
        # 获取参数
        data = json.loads(request.body.decode())
        username = data.get('name')
        user = request.user
        # User.objects.filter(id=user.id).update(username=username)

        user.username = username
        user.save()
        return JsonResponse({'errno': RET.OK, 'errmsg': '修改成功'})


class UserAuthView(LoginRequiredJSONMixin, View):
    """用户实名认证"""
    def get(self, request):
        # 显示认证信息
        user = request.user
        data = {
            'real_name': user.real_name,
            'id_card': user.id_card
        }

        return JsonResponse({"errno": RET.OK, "errmsg": '认证信息查询成功',  "data": data})

    def post(self, request):
        # 保存用户认证信息，数据库中添加字段
        dict_data = json.loads(request.body.decode())
        real_name = dict_data.get("real_name")
        id_card = dict_data.get("id_card")

        if not all([real_name, id_card]):
            return JsonResponse({"errno": RET.PARAMERR, "errmsg": "参数错误"})

        user = request.user

        user.real_name = real_name
        user.id_card = id_card
        user.save()


        return JsonResponse({"errno": RET.OK, "errmsg": '认证信息保存成功'})


